using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    public Transform spawn;
    public Transform shutPos;
    public Transform circle;
    public Transform circleChild;

    public GameObject pinPrefab;
    private Pin pinSpawn;
    private Pin pinWaitshut;

    private bool waitShut = false;
    private bool shutting = false;

    public bool GameStateIsGameOver;
    private Camera _camera;

    void Start()
    {
        //circleChild.position = circle.position - new Vector3(0, -1, 0);
        _camera = Camera.main;
        //GameStateIsGameOver = false;
        SpawnPin();
    }

    //检测是否在等待发射，不是等待状态，就把针发射到发射点
    void CheckShutPosIsHavePin()
    {
        if (waitShut)
            return;
        pinSpawn.Move(shutPos.position);
        if (Vector3.Distance(pinSpawn.transform.position, shutPos.position) < 0.05f)
        {
            pinWaitshut = pinSpawn;
            pinSpawn = null;
            waitShut = true;
            SpawnPin();
        }
    }

    private void ShootingPin()
    {
        if (!shutting)
            return;
        pinWaitshut.Move(circleChild.position);
        if (Vector3.Distance(pinWaitshut.transform.position, circleChild.position) < 0.05f)
        {
            pinWaitshut.transform.position = circleChild.position;
            pinWaitshut.transform.parent = circle;
            pinWaitshut = null;
            waitShut = false;
            shutting = false;
        }
    }

    //出生一颗针 
    void SpawnPin()
    {
        GameObject obj = Instantiate(pinPrefab, spawn.transform.position, pinPrefab.transform.rotation);
        pinSpawn = obj.GetComponent<Pin>();
    }

    private int animationSpeed = 2;

    public void GameOver()
    {
        circle.gameObject.GetComponent<Circle>().enabled = false;
        _camera.orthographicSize = Mathf.Lerp(_camera.orthographicSize, 4, animationSpeed * Time.deltaTime);
        _camera.backgroundColor = Color.Lerp(_camera.backgroundColor, Color.black, animationSpeed * Time.deltaTime);
        if (Mathf.Abs(_camera.orthographicSize - 5) < 0.05f)
        {
            Debug.Log("游戏结束了");
            StartCoroutine(StartGameScene());
        }
    }

    IEnumerator StartGameScene()
    {
        yield return new WaitForSeconds(3);
        SceneManager.LoadScene(0);
    }


    void Update()
    {
        CheckShutPosIsHavePin();
        if (Input.GetMouseButtonDown(0) && waitShut)
        {
            if (GameStateIsGameOver)
                return;
            shutting = true;
        }

        ShootingPin();
        if (GameStateIsGameOver)
        {
            GameOver();
        }
    }
}